<template>
  <div>
    <div class="search-wrapper">
      <input class="search-input" v-model="keyWords" type="text" placeholder="请输入城市名" />
    </div>
    <div v-show="keyWords" class="search-list" ref="scroll">
      <ul>
        <li v-for="item of list" :key="item.id" @click="handleCityClick(item.name)" class="search-list__item border-bottom">{{item.name}}</li>
        <li v-show="!list.length" class="search-list__item border-bottom">没有找到相关搜索项</li>
      </ul>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyWords: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleCityClick (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  watch: {
    keyWords () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyWords) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyWords) > -1 || value.name.indexOf(this.keyWords) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.scroll, {
      click: true
    })
  }
}
</script>

<style lang="scss" scoped>
  @import "~styles/scss/variable.scss";
  .search-wrapper {
    padding: .1rem .2rem;
    background: $color-primary;
    .search-input {
      width: 100%;
      box-sizing: border-box;
      height: .62rem;
      border-radius: .04rem;
      text-align: center;
      font-size: $fontSize-regular;
    }
  }
  .search-list {
    position: absolute;
    overflow: hidden;
    z-index: 100;
    top: 1.7rem;
    right: 0;
    bottom: 0;
    left: 0;
    background: #eee;
    &__item {
      background: #fff;
      padding: .22rem .2rem;
      color: $color-text-regular;
      font-size: $fontSize-regular;
    }
  }
</style>
